import routes from '@/routes'
import { useRoutes } from 'react-router-dom'
import { Suspense, useEffect } from 'react'
import PageLoading from '@/components/page-loading'
import { getUserInfo, getUserRoles } from '@/api/user'
import { getApplyNumber } from '@/api/admin'
import { getLink } from '@/api'
import { currUserRoles, applyNumber, shareLink } from '@/store'
import { useRecoilState, useSetRecoilState } from 'recoil'
import { useCheckLogin, useUserInfo } from '@/utils/hooks'
import { handleLocalUserInfo } from '@/utils/utils'
import { VALID_ROLE_CODE, PARTNER_ID, ADMIN_ID } from '@/constant'
import { useLocation } from 'react-router-dom'
function App() {
  const { pathname } = useLocation()
  const { getUserToken } = handleLocalUserInfo()
  useCheckLogin()
  const { setUser } = useUserInfo()
  const setShareLink = useSetRecoilState(shareLink)
  const setApplyNumber = useSetRecoilState(applyNumber)
  const [currUserRole, setCurrUserRole] = useRecoilState(currUserRoles)
  // 获取用户信息
  const getInfo = async () => {
    const res = await getUserInfo()
    if (!res.code) {
      setUser(res.data)
    }
  }

  // 管理员获取待审核的角色数
  const getNums = async () => {
    const res = await getApplyNumber()
    setApplyNumber(res.data.total || 0)
  }

  // 角色信息获取，划分权限，路由
  const fetchRoles = async () => {
    const res = await getUserRoles()
    const routeArr = res?.data?.list || []
    // 先去找可用的角色第一个，找不到则拿营销伙伴角色
    const current =
      routeArr.find((item) => item.status === VALID_ROLE_CODE) || routeArr.find((item) => item.actorType === PARTNER_ID)

    setCurrUserRole({
      list: routeArr,
      current,
    })
  }

  //获取分享链接
  const fetchShareLink = async () => {
    const res = await getLink()
    if (!res.code) {
      setShareLink(res.data?.link)
    }
  }
  useEffect(() => {
    if (getUserToken().token) {
      getInfo()
      fetchRoles()
      fetchShareLink()
    } else {
      if (pathname !== '/login' && pathname !== '/') {
        window.location.replace('/login')
      }
      setCurrUserRole({ current: {}, list: [] })
    }
  }, [])

  //根据角色来获取数据
  useEffect(() => {
    // 当前是管理员
    if (currUserRole && currUserRole.current?.actorType === ADMIN_ID) {
      getNums()
    }
  }, [currUserRole])

  if (!currUserRole) {
    return <PageLoading />
  }

  const MainRoutes = ({ user }) => {
    const type = user.status === VALID_ROLE_CODE ? user.actorType : 0 //没有可用的角色则到开通页面去
    const element = useRoutes(routes[type])
    return <Suspense fallback={<PageLoading />}>{element}</Suspense>
  }
  return <MainRoutes user={currUserRole?.current || {}} />
}

export default App
